<template>
    <div class="service-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="服务名称:">
                                <el-input 
                                    v-model="searchForm.serviceName" 
                                    placeholder="输入服务名称" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="服务种类:">
                                <el-select 
                                    v-model="searchForm.serviceType" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="咨询服务" value="1" />
                                    <el-option label="预约服务" value="2" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="发布时间:">
                                <el-date-picker
                                    v-model="searchForm.dateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="请选择日期"
                                    end-placeholder="请选择日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    style="width: 240px"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询结果</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增服务按钮 -->
        <div class="add-section">
            <el-button type="primary" @click="handleAddService">新增服务</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="serviceName" label="服务名称" align="center" />
                    <el-table-column prop="serviceTypeName" label="服务种类" width="120" align="center" />
                    <el-table-column prop="serviceCategory" label="服务类型" align="center"/>
                    <el-table-column prop="expertName" label="专家名称" align="center"/>
                    <el-table-column prop="price" label="价格" width="120" align="center">
                        <template #default="{ row }">
                            ¥{{ row.price }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="serviceStatus" label="上下架状态" width="120" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getServiceStatusType(row.serviceStatus)">
                                {{ getServiceStatusText(row.serviceStatus) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="approvalStatus" label="审批状态" width="120" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getApprovalStatusType(row.approvalStatus)">
                                {{ getApprovalStatusText(row.approvalStatus) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
                        <template #default="{ row }">
                            {{ formatDateTime(row.publishTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button 
                                v-if="row.serviceStatus === 1" 
                                type="primary" 
                                size="small" 
                                @click="handleView(row)"
                            >
                                查看
                            </el-button>
                            <el-button type="info" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.current }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getExpertServicePage, deleteExpertService } from '@/api/product/expert-service';

const router = useRouter();

// 搜索表单
const searchForm = reactive({
    serviceName: '',
    serviceType: '',
    dateRange: []
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);

// 分页数据
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
});

// 上下架状态类型
const getServiceStatusType = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: 'danger',   // 下架
        1: 'success'   // 上架
    };
    return statusMap[status] || 'info';
};

// 上下架状态文本
const getServiceStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '下架',
        1: '上架'
    };
    return statusMap[status] || '未知';
};

// 审批状态类型
const getApprovalStatusType = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: 'warning',  // 待审批
        1: 'success',  // 审批通过
        2: 'danger',   // 审批拒绝
        3: 'info'      // 审批中
    };
    return statusMap[status] || 'info';
};

// 审批状态文本
const getApprovalStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '待审批',
        1: '审批通过',
        2: '审批拒绝',
        3: '审批中'
    };
    return statusMap[status] || '未知';
};

// 时间格式化
const formatDateTime = (dateStr: string) => {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '/');
};

// 加载数据
const loadData = async () => {
    try {
        loading.value = true;
        const params = {
            current: pagination.current,
            size: pagination.size,
            ...(searchForm.serviceName && { serviceName: searchForm.serviceName }),
            ...(searchForm.serviceType && { serviceType: searchForm.serviceType }),
            ...(searchForm.dateRange && searchForm.dateRange.length === 2 && {
                startTime: searchForm.dateRange[0],
                endTime: searchForm.dateRange[1]
            })
        };
        
        const res = await getExpertServicePage(params);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
        } else {
            ElMessage.error('获取专家服务列表失败');
        }
    } catch (error) {
        console.error('加载数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 搜索方法
const handleSearch = () => {
    pagination.current = 1;
    loadData();
};

// 重置方法
const handleReset = () => {
    searchForm.serviceName = '';
    searchForm.serviceType = '';
    searchForm.dateRange = [];
    pagination.current = 1;
    loadData();
};

// 分页方法
const handlePageChange = (page: number) => {
    pagination.current = page;
    loadData();
};

const handleSizeChange = (size: number) => {
    pagination.size = size;
    pagination.current = 1;
    loadData();
};

// 新增服务
const handleAddService = () => {
    router.push('/service-form');
};

// 查看服务
const handleView = (row: any) => {
    // 根据服务种类确定类型参数
    const serviceType = row.serviceCategory === '咨询服务' ? 'consultation' : 'appointment';
    router.push(`/service-detail/${row.id}/${serviceType}`);
};

// 编辑服务
const handleEdit = (row: any) => {
    router.push(`/service-form/${row.id}`);
};

// 删除服务
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除服务 "${row.serviceName}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        loading.value = true;
        const res = await deleteExpertService(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200) {
            ElMessage.success('删除成功');
            loadData();
        } else {
            ElMessage.error((responseData && responseData.msg) || '删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

// 页面初始化
onMounted(() => {
    loadData();
});
</script>

<style scoped>
.service-list-container {
    padding: 20px;
}

/* 搜索区域 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.search-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 新增按钮区域 */
.add-section {
    margin-bottom: 20px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .service-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }
    
    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    
    .pagination-content {
        flex-direction: column;
        gap: 15px;
        align-items: center;
    }
}
</style>
